<template>
  <div class="upload">
    <div v-if="!finish" class="title">{{ title }}</div>
    <div v-if="!finish" class="Data">
      <van-uploader
        v-model="value_1"
        class="uploader"
        v-bind="captureAttrs"
        accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
        :after-read="afterRead"
        :max-count="maxCount"
        :multiple="multiple"
        @delete="removeFile"
      />
    </div>
    <div v-if="finish" class="noData">
      <div>
        <img src="@/assets/success.svg" alt="">
      </div>
      <div class="submit_title">上传成功</div>
    </div>
    <div v-if="!finish" class="btn_box">
      <div class="btn" @click="submit">上传</div>
    </div>
  </div>
</template>

<script>
  import { queryToken, saveUploadurl } from '@/api'
  // import watermark from "watermarkjs";
  import * as qiniu from 'qiniu-js'
  import { Toast } from 'vant'
  import { param2Obj } from '@/utils'
  import store from '@/store'
  // import moment from "moment";
  export default {
    name: 'phone-upload',
    data() {
      return {
        params: {
          tenantId: '',
          uuid: ''
        },
        finish: false,
        title: '附件上传',
        address: '',
        watermark: '',
        maxCount: 1,
        fileList: [],
        fileUrls: [],
        tokenInfo: {},
        qiniuData: {
          // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: {},
          bucket: ' '
        },
        value_1:
          this.value && this.value !== ''
            ? this.value.split(',').map(item => {
              return {
                url: item
              }
            })
            : [],
        attrs: {}
      }
    },
    computed: {
      multiple() {
        return this.maxCount > 1
      },
      // 是否配置了只允许拍照上传
      captureAttrs() {
        if (this.attrs.capture) {
          return {
            capture: 'camera'
          }
        } else {
          return {}
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        const url = window.location.href
        const searchParams = param2Obj(url) // 路径上的所有参数的对象
        this.maxCount = searchParams.maxCount || 1
        // 获取路径上的参数lang
        if (searchParams.lang) {
          // 如果store.state.language的值不包含this.$route.query.lang的值，则刷新页面
          if (!store.state.language.includes(this.$route.query.lang)) {
            window.location.reload()
          }
          this.$store.commit('CHANGE_LANGUAGE', searchParams.lang)
        }
        if (searchParams.uuid) this.params.uuid = searchParams.uuid
        if (searchParams.capture === '1') this.attrs.capture = true
        if (searchParams.token) this.qiniuData.token = searchParams.token
        else this.attrs.capture = false
        if (searchParams.title && searchParams.title !== 'undefined') this.title = searchParams.title
        else this.title = this.$t('Components.UploadImage')
        this.getQiniuyunUploadToken(searchParams.uuid)
        this.changeTitleClick()
      },
      async submit() {
        if (this.fileUrls.length === 0 || this.value_1.length !== this.fileUrls.length) {
          return
        }
        Toast.loading({
          duration: 0,
          overlay: true
        })
        const res = await saveUploadurl({
          uuid: this.params.uuid,
          url: this.fileUrls.join(',')
        })
        if (res.status === 200) {
          this.finish = true
          // Toast.success('上传成功')
          // 提交成功后关闭窗口
        }
        Toast.clear()
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken(uuid) {
        const res = await queryToken({ uuid })
        // this.tokenInfo = res.data
        this.qiniuData.token = res.data
        // this.qiniuData.bucket = res.data.bucket
        // this.qiniuData.key = res.data.filePath
        // this.domainName = res.data.domainName
      },
      removeFile(file, obj) {
        const index = obj.index
        this.fileUrls.splice(index, 1)
        this.value_1.splice(index, 1)
      },
      async afterRead(file) {
        // Toast.setDefaultOptions({ className: 'toast' })
        Toast.loading({
          duration: 0,
          overlay: true
        })
        if (file.length) { // 如果是多张图片
          file.forEach(async item => {
            await this.upload(item)
          })
        } else {
          await this.upload(file)
        }
        Toast.clear()
      // 水印
      // let _this = this;
      // var canvas = document.createElement("canvas");
      // var ctx = canvas.getContext("2d");
      // var img = new Image();
      // img.src = file.content;
      // img.crossOrigin = "anonymous"; // 添加 crossOrigin 属性
      // img.onload = function() {
      //   canvas.width = img.width;
      //   canvas.height = img.height;
      //   ctx.drawImage(img, 0, 0);
      //   let watermarkText =
      //     _this.address + " " + moment().format("YYYY-MM-DD HH:mm:ss");
      //   watermark([canvas.toDataURL()])
      //     .image(watermark.text.center(watermarkText, "32px Arial", "red"), {
      //       margin: 10,
      //       opacity: 0.5
      //     })
      //     .then(function(img) {
      //       const base64String = img.src.split(",")[1];
      //       const blob = _this.transBlob(base64String);
      //       _this.upload(blob, file);
      //     });
      // };
      // this.upload(file);
      },
      transBlob(base64String) {
        // 将 Base64 字符串转换为 ArrayBuffer 类型的二进制数据
        const binaryString = atob(base64String)
        const binaryData = new Uint8Array(binaryString.length)
        for (let i = 0; i < binaryString.length; i++) {
          binaryData[i] = binaryString.charCodeAt(i)
        }
        const arrayBuffer = binaryData.buffer

        // 将 ArrayBuffer 转换为 Blob 对象
        const blob = new Blob([arrayBuffer], {
          type: 'application/octet-stream'
        })
        return blob
      },
      upload(file) {
        const _this = this
        const fileName = new Date().getTime() + file.file.name
        const config = {
          // useCdnDomain: true, //cdn加速
          retryCount: 5, // 上传错误重新上传次数
          region: qiniu.region.z0
        }
        const observer = {
          next(res) {
            // res.total.percent 上传进度
            file.message = parseInt(res.total.percent) + '%'
          },
          error(code, message, isRequestError) {
            // 错误信息
            console.log(code)
            console.log(message)
            console.log(isRequestError)
          },
          complete(res) {
            _this.fileUrls.push(res.key)
            _this.value_1 = _this.fileUrls.map(item => {
              return {
                url: 'http://image.haoyunqi.com.cn/' + item
              }
            })
          }
        }

        const observable = qiniu.upload(
          file.file,
          this.qiniuData.key + '_' + fileName,
          this.qiniuData.token,
          {},
          config
        )
        observable.subscribe(observer) // 上传监听
      },
      /* 水印 */
      // upload1(blob, file) {
      //   const _this = this;
      //   const fileName = new Date().getTime() + file.file.name;
      //   let config = {
      //     // useCdnDomain: true, //cdn加速
      //     retryCount: 5, // 上传错误重新上传次数
      //     region: qiniu.region.z0
      //   };
      //   let observer = {
      //     next(res) {
      //       // res.total.percent 上传进度
      //       file.message = parseInt(res.total.percent) + "%";
      //     },
      //     error(code, message, isRequestError) {
      //       //错误信息
      //       console.log(code);
      //       console.log(message);
      //       console.log(isRequestError);
      //     },
      //     complete(res) {
      //       _this.fileUrls.push("//" + _this.domainName + "/" + res.key);
      //       console.log("//" + _this.domainName + "/" + res.key, "----");
      //       _this.value_1 = _this.fileUrls.map(item => {
      //         return {
      //           url: item
      //         };
      //       });
      //       Toast.clear();
      //     }
      //   };

      //   let observable = qiniu.upload(
      //     // file.file,
      //     blob,
      //     this.qiniuData.key + "_" + fileName,
      //     this.qiniuData.token,
      //     {},
      //     config
      //   );
      //   observable.subscribe(observer); //上传监听
      // },
      // 动态修改微信网页标题
      changeTitleClick() {
        const _this = this
        document.setTitle = function(t) {
          document.title = t
          const i = document.createElement('iframe')
          i.src = './favicon.ico'
          i.style.display = 'none'
          i.onload = function() {
            setTimeout(function() {
              i.remove()
            }, 9)
          }
          document.body.appendChild(i)
        }
        setTimeout(function() {
          const title = _this.title
          document.setTitle(title)
        }, 1000)
      }
    }
  }
</script>

<style lang="scss" scoped>
.upload {
  padding: 20px 32px;
  font-size: 366.2%;
  .title {
    margin: 40px 0;
    font-family: PingFang SC, PingFang SC-Bold;
    font-size: 0.8em;
    font-weight: 700;
    color: #303133;
  }
  /deep/ .toast {
    font-size: 1em;
  }
  .noData {
    padding-top: 3em;
    font-size: 0.8em;
    color: #666;
    text-align: center;
    img {
      width: 40vw;
    }
    .submit_title {
      margin-top: 2em;
      font-family: DIN, DIN-Medium;
      font-size: 1em;
      font-weight: 500;
      color: #323233;
      text-align: center;
    }
  }
  .Data {
    height: 50vh;
    .uploader {
      /deep/ .van-uploader__upload {
        width: 200px;
        height: 200px;
      }
      /deep/ .van-uploader__preview {
        margin: 0 16px 16px 0;
      }
      /deep/ .van-uploader__preview-image {
        width: 200px;
        height: 200px;
      }
      /deep/ .van-uploader__preview-delete {
        width: 40px;
        height: 40px;
      }
      /deep/ .van-uploader__preview-delete-icon {
        font-size: 0.8em;
      }
      /deep/ .van-uploader__upload-icon {
        font-size: 1em;
      }
    }
  }
  .btn_box {
    display: flex;
    justify-content: center;
    .btn {
      width: 100%;
      padding: 40px 0;
      margin-top: 40px;
      font-size: 0.8em;
      line-height: 35px;
      color: #fff;
      text-align: center;
      background-color: #38aeb7;
      border-radius: 60px;
    }
  }
}
</style>
